/**
 * WebSocket服务封装类
 * 实现设备监控数据的实时推送
 */
class DeviceWebSocketService {
  constructor() {
    this.ws = null;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.reconnectInterval = 3000;
    this.heartbeatInterval = 30000;
    this.heartbeatTimer = null;
    this.reconnectTimer = null;
    this.listeners = new Map();
    this.isConnected = false;
    this.isConnecting = false;
    this.url = '';
    this.messageQueue = [];
    this.lastHeartbeat = Date.now();
  }

  /**
   * 连接WebSocket
   * @param {string} url WebSocket连接地址
   */
  connect(url = process.env.VUE_APP_WS_URL || 'ws://localhost:8081/ws/device-monitor') {
    if (this.isConnecting || this.isConnected) {
      console.log('WebSocket已连接或正在连接中');
      return Promise.resolve();
    }

    this.url = url;
    this.isConnecting = true;

    console.log('🔌 尝试连接WebSocket:', url);

    return new Promise((resolve, reject) => {
      try {
        this.ws = new WebSocket(url);

        // 设置连接超时
        const connectTimeout = setTimeout(() => {
          if (this.isConnecting) {
            console.error('❌ WebSocket连接超时');
            this.isConnecting = false;
            this.ws.close();
            reject(new Error('WebSocket连接超时'));
          }
        }, 10000); // 10秒超时

        this.setupEventHandlers(resolve, reject, connectTimeout);
      } catch (error) {
        console.error('❌ WebSocket连接失败:', error);
        this.isConnecting = false;
        reject(error);
      }
    });
  }

  /**
   * 设置WebSocket事件处理器
   */
  setupEventHandlers(resolve = null, reject = null, connectTimeout = null) {
    this.ws.onopen = (event) => {
      console.log('✅ WebSocket连接成功');
      this.isConnected = true;
      this.isConnecting = false;
      this.reconnectAttempts = 0;

      // 清除连接超时
      if (connectTimeout) {
        clearTimeout(connectTimeout);
      }

      // 启动心跳检测
      this.startHeartbeat();

      // 发送队列中的消息
      this.flushMessageQueue();

      // 触发连接成功事件
      this.emit('connected', event);

      // 解析Promise
      if (resolve) {
        resolve(event);
      }
    };

    this.ws.onmessage = (event) => {
      try {
        const message = JSON.parse(event.data);
        this.handleMessage(message);
      } catch (error) {
        console.error('解析WebSocket消息失败:', error, event.data);
      }
    };

    this.ws.onclose = (event) => {
      console.log('🔌 WebSocket连接关闭:', event.code, event.reason);
      this.isConnected = false;
      this.isConnecting = false;

      // 清除连接超时
      if (connectTimeout) {
        clearTimeout(connectTimeout);
      }

      this.stopHeartbeat();

      // 触发连接关闭事件
      this.emit('disconnected', event);

      // 如果不是主动关闭且在连接阶段，拒绝Promise
      if (reject && event.code !== 1000) {
        reject(new Error(`WebSocket连接关闭: ${event.code} ${event.reason}`));
      }

      // 如果不是主动关闭，则尝试重连
      if (event.code !== 1000) {
        this.handleReconnect();
      }
    };

    this.ws.onerror = (error) => {
      console.error('❌ WebSocket连接错误:', error);
      this.isConnecting = false;

      // 清除连接超时
      if (connectTimeout) {
        clearTimeout(connectTimeout);
      }

      this.emit('error', error);

      // 拒绝Promise
      if (reject) {
        reject(error);
      }
    };
  }

  /**
   * 处理接收到的消息
   * @param {Object} message 消息对象
   */
  handleMessage(message) {
    const { type, data, timestamp } = message;

    console.log('📨 WebSocket收到消息:', { type, dataLength: Array.isArray(data) ? data.length : 'N/A' });

    switch (type) {
      case 'CONNECTION_SUCCESS':
        console.log('WebSocket连接确认:', data);
        break;
      case 'DEVICE_STATUS_UPDATE':
        console.log('📊 设备状态更新:', Array.isArray(data) ? data.length + '个设备' : data);
        this.emit('deviceStatusUpdate', data);
        break;
      case 'DEVICE_INFO_UPDATE':
        console.log('📊 设备信息更新:', Array.isArray(data) ? data.length + '个设备' : data);
        this.emit('deviceInfoUpdate', data);
        // 同时触发加速度数据更新事件（因为设备信息包含加速度数据）
        if (Array.isArray(data)) {
          data.forEach(deviceInfo => {
            if (deviceInfo.deviceId && (
              deviceInfo.xrms !== undefined || deviceInfo.yrms !== undefined || deviceInfo.zrms !== undefined ||
              deviceInfo.xpeak !== undefined || deviceInfo.ypeak !== undefined || deviceInfo.zpeak !== undefined
            )) {
              console.log('📈 从设备信息中提取加速度数据:', deviceInfo.deviceId);
              this.emit('accelerationDataUpdate', {
                ...deviceInfo,
                timestamp: deviceInfo.collectTime || timestamp || Date.now()
              });
            }
          });
        }
        break;
      case 'ACCELERATION_DATA_UPDATE':
        console.log('📈 加速度数据更新:', data);
        this.emit('accelerationDataUpdate', data);
        break;
      case 'HEARTBEAT_RESPONSE':
        this.lastHeartbeat = Date.now();
        console.log('💓 心跳响应');
        break;
      default:
        console.log('❓ 未知消息类型:', type, data);
        this.emit('message', message);
    }
  }

  /**
   * 发送消息
   * @param {Object} message 消息对象
   */
  send(message) {
    if (this.isConnected && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(message));
    } else {
      // 连接未建立时，将消息加入队列
      this.messageQueue.push(message);
    }
  }

  /**
   * 订阅设备加速度数据
   * @param {string} deviceId 设备ID
   * @param {string} latheName 设备名称
   */
  subscribeAccelerationData(deviceId, latheName) {
    this.send({
      type: 'SUBSCRIBE_ACCELERATION',
      data: {
        deviceId,
        latheName,
        timestamp: Date.now()
      }
    });
  }

  /**
   * 取消订阅设备加速度数据
   * @param {string} deviceId 设备ID
   */
  unsubscribeAccelerationData(deviceId) {
    this.send({
      type: 'UNSUBSCRIBE_ACCELERATION',
      data: {
        deviceId,
        timestamp: Date.now()
      }
    });
  }

  /**
   * 发送队列中的消息
   */
  flushMessageQueue() {
    while (this.messageQueue.length > 0) {
      const message = this.messageQueue.shift();
      this.send(message);
    }
  }

  /**
   * 启动心跳检测
   */
  startHeartbeat() {
    this.stopHeartbeat();
    this.heartbeatTimer = setInterval(() => {
      if (this.isConnected) {
        // 检查上次心跳时间
        if (Date.now() - this.lastHeartbeat > this.heartbeatInterval * 2) {
          console.log('心跳超时，重新连接');
          this.reconnect();
          return;
        }

        // 发送心跳
        this.send({
          type: 'HEARTBEAT',
          timestamp: Date.now()
        });
      }
    }, this.heartbeatInterval);
  }

  /**
   * 停止心跳检测
   */
  stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer);
      this.heartbeatTimer = null;
    }
  }

  /**
   * 处理重连
   */
  handleReconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('WebSocket重连次数超过限制，停止重连');
      this.emit('reconnectFailed');
      return;
    }

    this.reconnectAttempts++;
    console.log(`WebSocket重连尝试 ${this.reconnectAttempts}/${this.maxReconnectAttempts}`);

    this.reconnectTimer = setTimeout(() => {
      this.reconnect();
    }, this.reconnectInterval * this.reconnectAttempts);
  }

  /**
   * 重新连接
   */
  reconnect() {
    this.disconnect();
    this.connect(this.url);
  }

  /**
   * 断开连接
   */
  disconnect() {
    this.stopHeartbeat();

    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer);
      this.reconnectTimer = null;
    }

    if (this.ws) {
      this.ws.close(1000, '主动断开连接');
      this.ws = null;
    }

    this.isConnected = false;
    this.isConnecting = false;
    this.messageQueue = [];
  }

  /**
   * 添加事件监听器
   * @param {string} event 事件名称
   * @param {Function} callback 回调函数
   */
  on(event, callback) {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, []);
    }
    this.listeners.get(event).push(callback);
  }

  /**
   * 移除事件监听器
   * @param {string} event 事件名称
   * @param {Function} callback 回调函数
   */
  off(event, callback) {
    if (this.listeners.has(event)) {
      const callbacks = this.listeners.get(event);
      const index = callbacks.indexOf(callback);
      if (index > -1) {
        callbacks.splice(index, 1);
      }
    }
  }

  /**
   * 触发事件
   * @param {string} event 事件名称
   * @param {*} data 事件数据
   */
  emit(event, data) {
    if (this.listeners.has(event)) {
      this.listeners.get(event).forEach(callback => {
        try {
          callback(data);
        } catch (error) {
          console.error(`事件处理器执行失败 [${event}]:`, error);
        }
      });
    }
  }

  /**
   * 获取连接状态
   */
  getConnectionState() {
    return {
      isConnected: this.isConnected,
      isConnecting: this.isConnecting,
      reconnectAttempts: this.reconnectAttempts,
      readyState: this.ws ? this.ws.readyState : WebSocket.CLOSED
    };
  }
}

// 导出类，而不是实例
export default DeviceWebSocketService;
